package keeto.com.vn.classified.ui;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import keeto.com.vn.classfied.model.Area;
import keeto.com.vn.classified.core.ClassifiedCore;
import keeto.com.vn.classified.core.ClassifiedListener;
import keeto.com.vn.classified.database.BuiltinService;
import keeto.com.vn.classified.database.BuiltinServiceManager;
import keeto.com.vn.classified.manager.IAManager;
import keeto.com.vn.classified.network.IProtocol;
import keeto.com.vn.classified.utils.ImageUtilities;
import keeto.com.vn.classified.utils.PictureSizeUtils;
import keeto.com.vn.classified.widgets.ChangeAvatarDialog;
import keeto.com.vn.classified.widgets.OneRowGridView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore.MediaColumns;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.droid4you.util.cropimage.CropImage;

public class HandBookActivity extends Activity implements OnClickListener,
OnItemClickListener {

	private static final String TAG = "MeActivity";
	public static final String EXTRA_BACK = "BackText";
	private ImageButton btnBack;
	private TextView tvTitle;
	private ImageView btnSearch;
	private LinearLayout llUsername;
	private ImageView imgAvatar;
	private TextView tvName;
	private OneRowGridView mGridView;
	private Area mArea = null;
	private BuiltinServiceManager mServiceManager;
	private BuiltinService service;
	private RelativeLayout rlProfile;
	private LayoutInflater mInflater; 
	private AlertDialog dialog = null;

	public static final int INDEX_FAVOR = 0;
	public static final int INDEX_MY_PUBLISH = 1;
	public static final int INDEX_HISTORY = 2;
	private static final int CROP_FROM_CAMERA = 0;

	public static final int CAMERA_RESULT = 100;
	public static final int PICK_FROM_CALLERY = 200;
	private static final int PICK_FROM_LIBRARY = 300;
	private String mFilePath = "";
	private Uri mUri = null;
	private Bitmap mPhoto = null;
	private Bitmap newAvartar = null;
	private HandbookListener listener = new HandbookListener();
	private MyHandler handler = new MyHandler();

	public static void actionLaunchIntent(Context context) {
		Intent i = new Intent(context, HandBookActivity.class);
		context.startActivity(i);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ia_me_activity);
		mServiceManager = BuiltinServiceManager.getInstance(this);
		service = mServiceManager.getBuitinService();
		mInflater = LayoutInflater.from(this);
		mArea = IAManager.getInstance(this).getMyArea();
		initUIComponent();
	}

	private void initUIComponent(){
		rlProfile = (RelativeLayout)findViewById(R.id.rlProfile);
		btnBack = (ImageButton)findViewById(R.id.btn_sub_title_back);
		tvTitle = (TextView)findViewById(R.id.tv_sub_title_text);
		btnSearch = (ImageView)findViewById(R.id.btn_sub_title_search_home);
		btnSearch.setVisibility(View.GONE);
		llUsername = (LinearLayout)findViewById(R.id.ll_Username);
		imgAvatar = (ImageView)findViewById(R.id.img_avatar);
		tvName = (TextView)findViewById(R.id.tvName);
		mGridView = (OneRowGridView)findViewById(R.id.grid_handbook);
		tvTitle.setText(this.getResources().getString(R.string.title_handbook));
		if (service != null){
			tvName.setText(service.getUserName());
			byte[] src = service.getDisplayAvatar();
			if (src != null){
				Bitmap bmp = ImageUtilities.byteArray2Bimap(src);
				if (bmp == null){
					imgAvatar.setImageResource((R.drawable.no_avatar));
				}else{
					imgAvatar.setImageBitmap(ImageUtilities.getRoundedRectBitmap(bmp));
				}
			}else{
				imgAvatar.setImageResource((R.drawable.no_avatar));
			}
		}

		ArrayList<HashMap<String, Object>> functionsList = initFunctionData();
		SimpleAdapter saImageItems = new SimpleAdapter(this,functionsList,R.layout.ia_home_panel_item, new String[] { "image", "text" },new int[] { R.id.image, R.id.text });
		mGridView.setAdapter(saImageItems);
		mGridView.setOnItemClickListener(this);
		llUsername.setOnClickListener(this);
		imgAvatar.setOnClickListener(this);
		btnBack.setOnClickListener(this);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mFilePath = savedInstanceState.getString("filePath");
		mUri = Uri.fromFile(new File(mFilePath));
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("filePath", mFilePath);
	}


	public ArrayList<HashMap<String, Object>> initFunctionData() {

		ArrayList<HashMap<String, Object>> functionList = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> map1 = new HashMap<String, Object>();
		map1.put("image", R.drawable.icon_favorite_selector);
		map1.put("text", getString(R.string.ia_me_item_favor));
		functionList.add(map1);

		HashMap<String, Object> map2 = new HashMap<String, Object>();
		map2.put("image", R.drawable.icon_posted_selector);
		map2.put("text", getString(R.string.ia_me_item_my_publish));
		functionList.add(map2);

		HashMap<String, Object> map3 = new HashMap<String, Object>();
		map3.put("image", R.drawable.icon_history_selector);
		map3.put("text", getString(R.string.ia_me_item_history));
		functionList.add(map3);
		return functionList;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_sub_title_back:
			this.finish();
			break;
		case R.id.ll_Username:
			UserProfileActivity.actionLaunch(HandBookActivity.this);
			break;
		case R.id.img_avatar:
			if (hasStorage(true)) {
				mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()
						+ "/pic_" + String.valueOf(System.currentTimeMillis()) + ".jpg";

				mUri = Uri.fromFile(new File(mFilePath));
				ChangeAvatarDialog dialog = new ChangeAvatarDialog(HandBookActivity.this,mUri);
				dialog.show();
			} else {
				Toast.makeText(this,
						getString(R.string.alert_no_external_staorage),
						Toast.LENGTH_SHORT).show();
			}
			break;

		default:
			break;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		switch (position) {
		case INDEX_FAVOR:
			FavoritesActivity.actionViewFavorites(HandBookActivity.this);
			break;

		case INDEX_MY_PUBLISH:
			FavoritesActivity.actionViewPosted(HandBookActivity.this);
			break;

		case INDEX_HISTORY:
			FavoritesActivity.actionViewHistory(HandBookActivity.this);
			break;

		}
	}
	public boolean hasStorage(boolean requireWriteAccess) {
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		} else if (!requireWriteAccess
				&& Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			return true;
		}
		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}

		switch (requestCode) {

		case CROP_FROM_CAMERA: {
			final Bundle extras = data.getExtras();
			if (extras != null) {
				mPhoto = extras.getParcelable("data");
				if (mPhoto != null) {
					int avartarSize = PictureSizeUtils.getImAvartarSize(
							MainApplication.getScreenWidth(), MainApplication.getScreenHeight());

					Bitmap avartar = ImageUtilities.getResizedBitmapProfile(
							mPhoto, getBaseContext());
					Log.d(TAG, "CROP_FROM_CAMERA" + avartarSize);
					newAvartar = avartar;
					imgAvatar.setImageBitmap(ImageUtilities.getRoundedRectBitmap(avartar));
					handler.changeAvatar();
				}
			}
		}
		break;
		case CAMERA_RESULT:
			Log.d(TAG, "CAMERA_RESULT");
			int size = PictureSizeUtils.getUploadAvartarMaxSize();

			Intent intent = new Intent(this, CropImage.class);
			// here you have to pass absolute path to your file
			intent.putExtra("outputX", size);// screenSize
			intent.putExtra("outputY", size);
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("image-path", mUri.getPath());
			intent.putExtra("scale", true);
			intent.putExtra("return-data", true);
			startActivityForResult(intent, CROP_FROM_CAMERA);
			break;

		case PICK_FROM_CALLERY: {
			Log.d(TAG, "PICK_FROM_CALLERY");
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaColumns.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			mFilePath = cursor.getString(columnIndex);
			cursor.close();
			if (!TextUtils.isEmpty(mFilePath)) {

				int size2 = PictureSizeUtils.getUploadAvartarMaxSize();

				mUri = Uri.fromFile(new File(mFilePath));
				Intent i = new Intent(this, CropImage.class);
				i.putExtra("outputX", size2);
				i.putExtra("outputY", size2);
				i.putExtra("aspectX", 1);
				i.putExtra("aspectY", 1);
				i.putExtra("image-path", mUri.getPath());
				i.putExtra("scale", true);
				i.putExtra("return-data", true);
				startActivityForResult(i, CROP_FROM_CAMERA);

			}
		}
		break;

		}
	}

	class HandbookListener extends ClassifiedListener{
		@Override
		public void finishChangeAvatar(final int returnCode, String msg) {
			// TODO Auto-generated method stub
			super.finishChangeAvatar(returnCode, msg);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (returnCode == IProtocol.STATUS_CODE_OK_200){
						try {
							service.setDisplayAvatar(ImageUtilities.bitmap2ByteArray(newAvartar,100, Bitmap.CompressFormat.JPEG));
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mServiceManager.saveBuitinService(service);

					}
					service = mServiceManager.getBuitinService();
					if (service != null){
						tvName.setText(service.getUserName());
						byte[] src = service.getDisplayAvatar();
						if (src != null){
							Bitmap bmp = ImageUtilities.byteArray2Bimap(src);
							if (bmp != null){
								imgAvatar.setImageBitmap(ImageUtilities.getRoundedRectBitmap(bmp));
							}
						}
					}

				}
			});
		}
	}

	class MyHandler extends Handler{
		public void changeAvatar() {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					try {
						ClassifiedCore.getInstance(HandBookActivity.this).taskChangeAvatar(listener, ImageUtilities.bitmap2ByteArray(newAvartar,100, Bitmap.CompressFormat.JPEG), service.getAuthKey(), mArea.getRemoteId());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
	}
}
